package com.zxt.content.copywriting.service.impl;

import com.alibaba.fastjson.JSON;
import com.zxt.content.common.utils.StringUtils;
import com.zxt.content.common.utils.ZXTCollectionsUtil;
import com.zxt.content.copywriting.enums.PushTypeEnum;
import com.zxt.content.copywriting.manager.PrivateCopywritingManager;
import com.zxt.content.copywriting.manager.PublicCopywritingManager;
import com.zxt.content.copywriting.manager.UserCopywritingConfigManager;
import com.zxt.content.copywriting.model.PrivateCopywriting;
import com.zxt.content.copywriting.model.PublicCopywriting;
import com.zxt.content.copywriting.model.UserCopywritingConfig;
import com.zxt.content.copywriting.service.CopywritingJobService;
import com.zxt.content.thirdParty.client.AmapClient;
import com.zxt.content.thirdParty.client.MailClient;
import com.zxt.content.thirdParty.client.WxPublicClient;
import com.zxt.content.thirdParty.req.PushCopywritingDTO;
import com.zxt.content.thirdParty.resp.LiveVO;
import com.zxt.content.thirdParty.resp.WeatherVO;
import com.zxt.content.user.manager.BUserManager;
import com.zxt.content.user.model.BUser;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * 文案定时任务业务逻辑层
 *
 * @author zxt
 */
@Service(value = "copywritingJobServiceImpl")
@AllArgsConstructor
@Slf4j
public class CopywritingJobServiceImpl implements CopywritingJobService {

    private final UserCopywritingConfigManager userCopywritingConfigManager;
    private final BUserManager bUserManager;
    private final PrivateCopywritingManager privateCopywritingManager;
    private final PublicCopywritingManager publicCopywritingManager;
    private final MailClient mailClient;
    private final WxPublicClient wxPublicClient;
    private final AmapClient amapClient;


    @Override
    public void dealPushCopywritingByEmail() {
        List<UserCopywritingConfig> configs = userCopywritingConfigManager.getEnablePushUser();

        if (ZXTCollectionsUtil.isEmpty(configs)) {
            log.info("没有需要发送邮件的用户");
            return;
        }

        List<Long> userIds = configs.stream().map(UserCopywritingConfig::getUserId).collect(Collectors.toList());

        List<BUser> users = bUserManager.listByIds(userIds);
        Map<Long, BUser> userMap = Optional.ofNullable(users).orElse(new ArrayList<>()).stream().collect(Collectors.toMap(BUser::getId, Function.identity()));

        PublicCopywriting publicCopywriting = publicCopywritingManager.randGetOne();

        for (UserCopywritingConfig config : configs) {
            PushCopywritingDTO dto = new PushCopywritingDTO();
            //校验提送类型是私有文案推送还是公共文案推送
            if (PushTypeEnum.PRIVATE.equal(config.getPushType())) {
                PrivateCopywriting privateCopywriting = privateCopywritingManager.randGetOneByUserId(config.getUserId());
                if (Objects.isNull(privateCopywriting)) {
                    continue;
                }
                dto.setContent(privateCopywriting.getContent());
            } else {
                if (Objects.isNull(publicCopywriting)) {
                    continue;
                }
                dto.setContent(publicCopywriting.getContent());
            }

            BUser bUser = userMap.get(config.getUserId());
            if (Objects.isNull(bUser)) {
                continue;
            }

            Integer hour = LocalDateTime.now().getHour();

            //如果为空代表没有推送时间限制
            if (StringUtils.isNotEmpty(config.getPushTime())) {
                List<Integer> times = JSON.parseArray(config.getPushTime(), Integer.class);
                if (!times.contains(hour)) {
                    //如果不处于当前设置的推送时间节点
                    continue;
                }
            }

            dto.setEmail(bUser.getEmail());
            dto.setSubject(bUser.getNickName());
            mailClient.smsPushCopywritingMail(dto);
        }
    }

    @Override
    public void dealPushCopywritingByWx() {
        List<String> openIds = wxPublicClient.getOpenIds();
        PublicCopywriting publicCopywriting = publicCopywritingManager.randGetOneAndAddPushNum();

        //文案长度如果大于198,更换文案推送
        while (publicCopywriting.getContent().length() > 198) {
            log.info("今日文案id:{} 长度超过微信公众号推送消息限制最大长度");
            publicCopywriting = publicCopywritingManager.randGetOneAndAddPushNum();
        }

        if (ZXTCollectionsUtil.isEmpty(openIds) || Objects.isNull(publicCopywriting)) {
            return;
        }

        String luoYang = "410300";
        String shangHai = "310000";

        WeatherVO weatherVO = amapClient.getWeather(luoYang);
        //处理数据
        LiveVO liveVO = dealLiveVO(weatherVO);

        List<String> strs = new ArrayList<>();
        strs.add("保持热爱，奔赴山海。");
        strs.add("面朝大海，春暖花开。");
        strs.add("候鸟迁徙，山河已秋。");
        Random random = new Random();
        String str = strs.get(random.nextInt(strs.size()));
        publicCopywriting.setTheme(str);

        for (String openId : openIds) {
            //推送文案
            boolean isTrue = wxPublicClient.pushCopywriting(openId, publicCopywriting, liveVO);
            if (!isTrue) {
                //推送失败，邮箱告警
                PushCopywritingDTO dto = new PushCopywritingDTO();
                dto.setContent("文案id:" + publicCopywriting.getId() + " 推送失败！");
                dto.setEmail("1480140172@qq.com");
                dto.setSubject("微信公众号推送文案失败告警!");
                mailClient.smsEmail(dto);
                //更换文案
                publicCopywriting = publicCopywritingManager.randGetOneAndAddPushNum();
                publicCopywriting.setTheme(str);
                //重推
                wxPublicClient.pushCopywriting(openId, publicCopywriting, liveVO);
            }
        }
    }

    private LiveVO dealLiveVO(WeatherVO weatherVO) {
        LiveVO liveVO = weatherVO.getLives().get(0);
        liveVO.setTemperature(liveVO.getWeather() + " " + liveVO.getTemperature() + "°");
        liveVO.setCity("洛阳城");
        try {
            Integer windpower = Integer.parseInt(liveVO.getWindpower());
            if (windpower.equals(4)) {
                //4级风
                liveVO.setWindpower("水摇扇影戏鱼惊 " + liveVO.getWindpower() + "级风");
            } else if (windpower > 4 && windpower <= 6) {
                //5-6级风
                liveVO.setWindpower("癫狂柳絮随风去 " + liveVO.getWindpower() + "级风");
            } else if (windpower > 6 && windpower <= 8) {
                //7-8
                liveVO.setWindpower("山雨欲来风满楼 " + liveVO.getWindpower() + "级风");
            } else if (windpower > 8) {
                //9-n
                liveVO.setWindpower("不恨狂风取花去 " + liveVO.getWindpower() + "级风");
            }
        } catch (Exception e) {
            //<=3级风
            liveVO.setWindpower("潭面无风镜未磨 " + liveVO.getWindpower() + "级风");
        }
        return liveVO;
    }


}
